package com.probox.common.entity.service.platfom.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.PlatformException;
import com.probox.common.core.exception.ProductException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.platfom.PlatformCmsClass;
import com.probox.common.entity.mapper.platfom.PlatformCmsClassMapper;
import com.probox.common.redis.service.RedisService;
import com.probox.platform.api.domain.PlatformApiCmsVo;
import com.probox.common.entity.domain.platfom.vo.PlatformCmsVo;
import com.probox.common.entity.domain.platfom.vo.PlatformCnsQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.query.QueryUtils;
import org.springframework.stereotype.Service;
import com.probox.common.entity.mapper.platfom.PlatformCmsMapper;
import com.probox.common.entity.domain.platfom.PlatformCms;
import com.probox.common.entity.service.platfom.IPlatformCmsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * (资讯/平台/公告)信息Service业务层处理
 *
 * @date 2021-06-11
 */
@Service
@Transactional
public class PlatformCmsServiceImpl extends ServiceImpl<PlatformCmsMapper, PlatformCms> implements IPlatformCmsService {
    @Autowired
    private PlatformCmsMapper platformCmsMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private PlatformCmsClassMapper platformCmsClassMapper;

    private final String sImg = "?imageslim";


    /**
     * 查询(资讯/平台/公告)信息
     *
     * @param cmsUid (资讯/平台/公告)信息ID
     * @return (资讯 / 平台 / 公告)信息
     */
    @Override
    public PlatformCms selectPlatformCmsById(Long cmsUid) {
        return this.getById(cmsUid);
    }

    /**
     * 查询(资讯/平台/公告)信息列表
     *
     * @param platformCms (资讯/平台/公告)信息
     * @return (资讯 / 平台 / 公告)信息
     */
    @Override
    public List<PlatformCmsVo> queryList(PlatformCms platformCms) {
        if (platformCms.getPlatformUid() == null) {
            Long platformId = SecurityUtils.getCustomerPlatformUid();
            if (platformId == null) {
                throw new BaseException("当前账号异常");
            }
            platformCms.setPlatformUid(platformId);
        }

        return platformCmsMapper.queryList(platformCms);
    }

    @Override
    public List<PlatformCmsVo> queryQuestion(){
        return platformCmsMapper.queryQuestion();
    }


    @Override
    public Integer queryListCount(PlatformCms platformCms) {
        if (platformCms.getPlatformUid() == null) {
            Long platformId = SecurityUtils.getCustomerPlatformUid();
            if (platformId == null) {
                throw new BaseException("当前账号异常");
            }
            platformCms.setPlatformUid(platformId);
        }
        QueryWrapper<PlatformCms> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(platformCms.getCmsTitle())) && platformCms.getCmsTitle() != null) {
            queryWrapper.like("CMS_TITLE", platformCms.getCmsTitle());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformCms.getCmsType())) && platformCms.getCmsType() != null) {
            queryWrapper.eq("CMS_TYPE", platformCms.getCmsType());
        }

        queryWrapper.orderByAsc("DATA_PRIORITY");
        return platformCmsMapper.selectList(queryWrapper).size();
    }


    /**
     * 新增(资讯/平台/公告)信息
     *
     * @param platformCms (资讯/平台/公告)信息
     * @return 结果
     */
    @Override
    public boolean insertPlatformCms(PlatformCms platformCms) {
        if (ObjectUtil.isNotEmpty(platformCms.getCmsContent())) {
            if (platformCms.getCmsContent().length() >= 1048576) {
                throw new BaseException("内容不能超过1m！");
            }
        }
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        DateTime date = DateUtil.date();
        platformCms.setCreateUid(userId);
        platformCms.setCreateName(username);
        platformCms.setCreateTime(date);
        platformCms.setUpdateUid(userId);
        platformCms.setUpdateName(username);
        platformCms.setUpdateTime(date);
        platformCms.setPlatformUid(SecurityUtils.getPlatformId());
        if (DataStatus.valid.getKey().equals(platformCms.getDataStatus())) {
            platformCms.setPublishTime(date);
            platformCms.setPublishUid(userId);
            platformCms.setPublishName(username);
            redisService.deleteObject(CachePrefix.PLATFORM_CNS + SecurityUtils.getPlatformId());
        }
        return this.save(platformCms);

    }

    /**
     * 修改(资讯/平台/公告)信息
     *
     * @param platformCms (资讯/平台/公告)信息
     * @return 结果
     */
    @Override
    public boolean updatePlatformCms(PlatformCms platformCms) {
        if (ObjectUtil.isNotEmpty(platformCms.getCmsContent())) {
            if (platformCms.getCmsContent().length() >= 1048576) {
                throw new BaseException("内容不能超过1m！");
            }
        }
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        DateTime date = DateUtil.date();
        platformCms.setUpdateUid(userId);
        platformCms.setUpdateName(username);
        platformCms.setUpdateTime(date);
        platformCms.setPlatformUid(SecurityUtils.getPlatformId());
        if (DataStatus.valid.getKey().equals(platformCms.getDataStatus())) {
            platformCms.setPublishTime(date);
            platformCms.setPublishUid(userId);
            platformCms.setPublishName(username);
        }
        redisService.deleteObject(CachePrefix.PLATFORM_CNS + SecurityUtils.getPlatformId());
        return this.updateById(platformCms);
    }

    /**
     * 批量删除(资讯/平台/公告)信息
     *
     * @param cmsUids 需要删除的(资讯/平台/公告)信息ID
     * @return 结果
     */
    @Override
    public boolean deletePlatformCmsByIds(Long[] cmsUids, String type) {
        UpdateWrapper<PlatformCms> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("CMS_UID", Arrays.asList(cmsUids));
        updateWrapper.eq("CMS_TYPE", type);
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        this.update(updateWrapper);
        return true;
    }

    /**
     * 小程序查询单独的信息
     *
     * @param query
     * @return
     */
    @Override
    public PlatformCms get(PlatformCnsQuery query) {
        QueryWrapper<PlatformCms> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        if (ObjectUtil.isNotEmpty(query.getCmsUid())) {
            queryWrapper.eq("CMS_UID", query.getCmsUid());
        }
        if (ObjectUtil.isNotEmpty(query.getCode())) {
            queryWrapper.eq("CMS_CLASS_CODE", query.getCode());
        }
        if (ObjectUtil.isNotEmpty(query.getTitle())) {
            queryWrapper.eq("CMS_TITLE", query.getTitle());
        }
        if (ObjectUtil.isNotEmpty(query.getType())) {
            queryWrapper.eq("CMS_TYPE", query.getType());
        }
        queryWrapper.eq("PLATFORM_UID", query.getPlatformUid());
        List<PlatformCms> platformCms = platformCmsMapper.selectList(queryWrapper);

        if (ObjectUtil.isEmpty(platformCms)) return null;
        PlatformCms rst = platformCms.get(0);
        QueryWrapper<PlatformCmsClass> wrapper = new QueryWrapper<>();
        wrapper.eq("CMS_CLASS_CODE", rst.getCmsClassCode());
        List<PlatformCmsClass> classList = platformCmsClassMapper.selectList(wrapper);
        if (classList.size()>0){
            rst.setCmsClassName(classList.get(0).getCmsClassName());
        }
        return rst;
    }

    /**
     * 查看详情
     *
     * @param cmsUid
     * @return
     */
    @Override
    public PlatformCmsVo get(Long cmsUid) {
        if (ObjectUtil.isEmpty(cmsUid)) throw new PlatformException("参数异常！");
        return platformCmsMapper.queryListOne(cmsUid);
    }

    /**
     * 店铺装修,取值
     *
     * @param cmsUid
     * @return
     */
    @Override
    public PlatformCms getData(Long cmsUid, Long uid) {
        if (ObjectUtil.isEmpty(cmsUid)) return null;
        String key = CachePrefix.PLATFORM_CNS + uid;
        Map<String, PlatformCms> map = redisService.getCacheMap(key);
        if (ObjectUtil.isEmpty(map)) {
            QueryWrapper<PlatformCms> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
            queryWrapper.eq("PLATFORM_UID", uid);
            List<PlatformCms> platformCms = platformCmsMapper.selectList(queryWrapper);
            // = new HashMap<>();
            platformCms.forEach(cms -> {
                if (ObjectUtil.isNotEmpty(cms)) {
                    if (ObjectUtil.isNotEmpty(cms.getCmsIcon())) {
                        if (!cms.getCmsIcon().startsWith(sImg)) cms.setCmsIcon(cms.getCmsIcon() + sImg);
                    }
                    if (ObjectUtil.isNotEmpty(cms.getTitleImgUrl())) {
                        StringBuffer stringBuffer = new StringBuffer();
                        String[] split = cms.getTitleImgUrl().split(",");
                        for (int i = 0; i < split.length; i++) {
                            if (0 > split[i].indexOf(sImg)) split[i] = split[i] + sImg;
                            stringBuffer.append("," + split[i]);
                        }
                        cms.setTitleImgUrl(stringBuffer.toString());
                        cms.setTitleImgUrl(cms.getTitleImgUrl().substring(1, cms.getTitleImgUrl().length()));
                    }
                    map.put(String.valueOf(cms.getCmsUid()), cms);
                }
            });
            redisService.setCacheMap(key, map);
            redisService.expire(key, 1L, TimeUnit.DAYS);
        }
        return map.get(String.valueOf(cmsUid));
    }

    @Override
    public Map<String, PlatformCms> getDataT(Long uid) {
        String key = CachePrefix.PLATFORM_CNS + uid;
        Map<String, PlatformCms> map = redisService.getCacheMap(key);
        if (ObjectUtil.isEmpty(map)) {
            QueryWrapper<PlatformCms> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
            queryWrapper.eq("PLATFORM_UID", uid);
            List<PlatformCms> platformCms = platformCmsMapper.selectList(queryWrapper);
            // = new HashMap<>();
            platformCms.forEach(cms -> {
                if (ObjectUtil.isNotEmpty(cms)) {
                    if (ObjectUtil.isNotEmpty(cms.getCmsIcon())) {
                        if (!cms.getCmsIcon().startsWith(sImg)) cms.setCmsIcon(cms.getCmsIcon() + sImg);
                    }
                    if (ObjectUtil.isNotEmpty(cms.getTitleImgUrl())) {
                        StringBuffer stringBuffer = new StringBuffer();
                        String[] split = cms.getTitleImgUrl().split(",");
                        for (int i = 0; i < split.length; i++) {
                            if (0 > split[i].indexOf(sImg)) split[i] = split[i] + sImg;
                            stringBuffer.append("," + split[i]);
                        }
                        cms.setTitleImgUrl(stringBuffer.toString());
                        cms.setTitleImgUrl(cms.getTitleImgUrl().substring(1, cms.getTitleImgUrl().length()));
                    }
                    map.put(String.valueOf(cms.getCmsUid()), cms);
                }
            });
            redisService.setCacheMap(key, map);
            redisService.expire(key, 1L, TimeUnit.DAYS);
        }
        return map;
    }

    /**
     * 查询所有平台为1的公告
     *
     * @param pageNum
     * @param type
     * @return
     */
    @Override
    public List<PlatformApiCmsVo> getCms(Long pageNum, String type) {
        List<PlatformApiCmsVo> list = new ArrayList<>();
        QueryWrapper<PlatformCms> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("CMS_TYPE", type);
        queryWrapper.eq("PLATFORM_UID", 1L);
        queryWrapper.last("limit  " + pageNum);
        List<PlatformCms> platformCms = platformCmsMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(platformCms)) return list;
        platformCms.forEach(cms -> {
            PlatformApiCmsVo vo = new PlatformApiCmsVo();
            BeanUtils.copyProperties(cms, vo);
            list.add(vo);
        });
        return list;
    }

}
